package com.vitas.coin.task;

import android.text.TextUtils;

import java.util.concurrent.Future;

public abstract class SilentTask implements ITask<Void> {
    private static final String TAG = "SilentTask";

    protected volatile int mThreadPriority;
    protected volatile boolean mCanceled = false;
    private Future future;
    protected int mStatus = Status.PENDING;
    protected String name;

    public SilentTask(String name) {
        this.name = name;
        this.mThreadPriority = android.os.Process.THREAD_PRIORITY_BACKGROUND;
    }

    ITaskStatus listener = null;

    @Override
    public SilentTask setStatusListener(ITaskStatus listener) {
        this.listener = listener;
        return this;
    }

    @Override
    public Void call() throws Exception {
        android.os.Process.setThreadPriority(this.mThreadPriority);
        setStatus(Status.RUNNING);
        if (!this.mCanceled) {
            String name = getName();
            if (!TextUtils.isEmpty(name)) {
                Thread.currentThread().setName(name);
            }
            try {
                this.runInBackground();
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
        setStatus(Status.FINISHED);
        return null;
    }

    @Override
    public void setStatus(int status) {
        if (mStatus != status && listener != null) {
            listener.onStatusChanged(status);
        }
        mStatus = status;
        if (status == Status.FINISHED) {
            if (listener != null) {
                listener.onTaskDone();
            }
            listener = null;
        }
    }

    /**
     * Override this method to handle result from a worker thread.
     *
     * @return
     */
    public abstract void runInBackground() throws Exception;

    @Override
    public int getStatus() {
        return this.mStatus;
    }

    @Override
    public boolean isCanceled() {
        return this.mCanceled;
    }

    @Override
    public void cancel() {
        if (future != null) {
            future.cancel(true);
        }
        this.mCanceled = true;
    }

    @Override
    public void setThreadPriority(int priority) {
        this.mThreadPriority = priority;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public void setFuture(Future future) {
        this.future = future;
    }
}
